<?php
namespace app\app\model;
use think\Model;
use think\Db;

class SignModel extends Model{

    public $user_id;
    protected $table = "a_sign";

    /**
     * 签到
     */
    public function sign(){
        //取出签到奖励
        $reward = Db::name('config')->where('option_key','eq','sign_reward')->find();
        $value  = explode(',',$reward['option_value']);
        //查询之前签到的数据
        $data = $this->where('user_id','eq',$this->user_id)->find();
        //判断之前签到次数
        $today = date('Y-m-d',time());
        $today = strtotime($today);
//        return $result = array('point'=>2);
        //非第一次签到
        if( $data['sign_time'] && $data['sign_time'] != 0 ){
            $time = $today - $data['sign_time'];
            $day  = intval($time/86400);
            //若相同
            if( $day == $data['status']){
                //连续签到
                if( $data['status'] >= 5 ){
                    $status = 5;
                }else{
                    $status = $data['status'] + 1;
                }
                $this->update(array('id'=>$data['id'],'status'=>$status));
                //插入签到表
                Db::name('user_sign')->insert(array('user_id'=>$this->user_id,'create_time'=>time()));
                //添加积分
                Db::query('update a_users set points = points +'.$value[$data['status']].' where id='.$this->user_id);
                return $result = array('point'=>$value[$data['status']]);
            }elseif( $day > intval($data['status']) ){
                //断签了
                $this->update(array('id'=>$data['id'],'status'=>1,'sign_time'=>$today));
                //插入签到表
                Db::name('user_sign')->insert(array('user_id'=>$this->user_id,'create_time'=>time()));
                //添加积分
                Db::query('update a_users set points = points +'.$value[0].' where id='.$this->user_id);
                return $result=array('point'=>$value[0]);
            }
        }else{
            //第一次签到
            $sign = array('id'=>$data['id'],'status'=>1,'sign_time'=>$today);
            $this->update($sign);
            //插入签到表
            Db::name('user_sign')->insert(array('user_id'=>$this->user_id,'create_time'=>time()));
            Db::query('update a_users set points = points +'.$value[0].' where id='.$this->user_id);
            return $result=array('point'=>$value[0]);
        }
    }
}